package com.qf.shopitem.listener;

import com.qf.common.constant.RabbitMqConstants;
import com.qf.entity.Goods;
import com.rabbitmq.client.Channel;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
public class ListenItemQueue {
    @Autowired
    private FreeMarkerConfig freeMarkerConfig;
    @Value("http://localhost/shop-resources")
    private String basepath;

    private ExecutorService executorService = Executors.newFixedThreadPool(5);
    @RabbitListener(queues = RabbitMqConstants.GOODS_QUEUE_ITEM)
    public void createITem(Goods goods, Message message, Channel channel) {

        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    Template template = freeMarkerConfig.getConfiguration().getTemplate("goodsItem.ftl");
                    //数据封装到map中
                    Map<String, Object> map = new HashMap<>();
                    map.put("goods", goods);
                    map.put("basepath",basepath);
                    /*加\\防止转译*/
                    if (!StringUtils.isEmpty(goods.getGpic())) {
                        map.put("gpicList", goods.getGpic().split("\\|"));
                    }
                    //classpth就是classes的路径
                    File file = ResourceUtils.getFile("classpath:static");
                    //获得绝对路径
                    String absolutePath = file.getAbsolutePath();
                    System.out.println(absolutePath);

                    //"D:\\Program Files\\2009\\finalProject\\shop-spring-09\\shop-item\\src\\main\\resources\\static\\"
                    //项目在同环境下。不一定在一个磁盘路径，所以要绝对路径替换
                    //通过模板引擎来生成静态html
                    template.process(map, new FileWriter(absolutePath + File.separator + goods.getId() + ".html"));
                    channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (TemplateException e) {
                    e.printStackTrace();
                }
            }
        });


    }
}
